package br.com.commerce.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.commerce.entity.AbstractBaseEntity;

@FacesConverter("entityConverter")
public class EntityConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		
		if (value == null || value.isEmpty()) return null;
		
		return component.getAttributes().get(value);
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		
		if (value == null || !isEntity(value)) return null;
		
		AbstractBaseEntity entity = (AbstractBaseEntity) value;
		
		if (entity.getId() == null) {
			return null;
		}

		String idEntity = entity.getId().toString();
		
		component.getAttributes().put(idEntity, value);
		
		return idEntity;
	}
	
	private boolean isEntity(Object value) {
		return value instanceof AbstractBaseEntity;
	}
}
